package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Autor;
import java.sql.Connection;

public class AutorDaoImpl implements AutorDao {

	Connection c;

	public AutorDaoImpl() {
		GenericDao gDao = new GenericDao();

		c = gDao.getConnection();

	}

	@Override
	public void salvaAutor(Autor autor) throws SQLException {
		String sql = "INSERT INTO autores VALUES (?,?)";
		PreparedStatement ps = c.prepareStatement(sql);

		ps.setInt(1, autor.getIdAutor());
		ps.setString(2, autor.getNomeAutor());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaAutor(Autor autor) throws SQLException {
		String sql = "UPDATE autores SET nomeAutor = ? WHERE idAutor = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, autor.getNomeAutor());
		ps.setInt(2, autor.getIdAutor());
		ps.execute();
		ps.close();

	}

	@Override
	public void excluiAutor(Autor autor) throws SQLException {
		String sql = "DELETE autores WHERE idAutor = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, autor.getIdAutor());
		ps.execute();
		ps.close();

	}

	@Override
	public Autor pesquisaAutor(Autor autor) throws SQLException {
		Autor au = new Autor();
		String sql = "SELECT idAutor, nomeAutor FROM autores WHERE idAutor = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, autor.getIdAutor());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			au.setIdAutor(rs.getInt("idAutor"));
			au.setNomeAutor(rs.getString("nomeAutor"));

		}
		ps.close();
		rs.close();
		return au;
	}

}
